#include <unistd.h>
#include <stdio.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdlib.h>

int main()
{
    //创建socket
    int serverFd = socket(AF_INET,SOCK_DGRAM,0);
    if (-1==serverFd)
    {
        printf("创建socket失败:%m\n");
        return -1;
    }
    printf("创建socket成功\n");
    //服务器协议地址簇
    struct sockaddr_in addr={0};
    addr.sin_family=AF_INET;
    addr.sin_addr.s_addr = inet_addr("0.0.0.0");
    addr.sin_port=htons(8000);
    //绑定
    int r = bind(serverFd,(struct sockaddr*)&addr,sizeof addr);
    if (-1==r)
    {
        printf("绑定失败:%m\n");
        close(serverFd);
        exit(-1);
    }
    printf("绑定成功\n");
    //通信
    char buff[1024];
    while (1)
    {
        r = recv(serverFd,buff,1023,0);
        if (r >0)
        {
            buff[r] = 0; //添加字符串结束符号
            printf("%d:%s\n",r,buff);
        }
    }
    return 0;
}